--- 晨硕超声波-管段 9600,偶,已经默认读取地址，不需要设置地址
--- 如果系数有问题，请用通用modbus
module(..., package.seeall)
local logtag = "chenshuo_csb"
local dtu, udtu = {}, {}
--local read_add = '00030000000185DB' --MODBUS地址
--local read_ins = '010300140002840F' --顺时流量
--local read_dat = '0103000E0002A5C8' --累积流量
local isIns = false --先读取累计流量
local val,ins,addr =0,0,nil
function setDtu(_dtu, _udtu)
    dtu, udtu = _dtu, _udtu
    if udtu and tonumber(udtu.dtype) == 6 then sys.taskInit(init) end
end
local function _pro(data) 
    if not addr then
        addr= tonumber((data:sub(4, 5)):toHex(),16)
        return
    end
    local v_hex = data:sub(6, 7)..data:sub(4, 5)
    if isIns then
        ins = tonumber(v_hex:toHex(), 16)/1000
        lcd.LCD_DATA[3]= "瞬时:"..ins
        isIns = false
    else
        val = tonumber(v_hex:toHex(), 16)/100
        lcd.LCD_DATA[3]= "累计:"..val
        isIns = true
    end
    usrdata.update({val,ins})
end
function init()
    power.openBoost()
    sys.wait(200)
	while true do
        if addr then
            if isIns then
                tools.modbus_send(3,addr,3,0x14,2) --20
            else
                tools.modbus_send(3,addr,3,0x0E,2) --14
            end
        else
            tools.modbus_send(3,0,3,0,1)
        end
        local result, d = sys.waitUntil("UART_READ_DONE_NEXT_3" , 5000)
        if result then
            if d then
                _pro(d)
            end
            sys.wait(5000)
        else
            lcd.LCD_DATA[3] = string.format("U%dD%d READ TIMEOUT",3,udtu.dtype)
        end
	end
end
